import 'package:flutter/material.dart';
import 'morse_translator.dart';
import 'morse_quiz.dart';

/// 摩尔斯电码学习页面
class MorseLearningPage extends StatefulWidget {
  const MorseLearningPage({super.key});

  @override
  State<MorseLearningPage> createState() => _MorseLearningPageState();
}

class _MorseLearningPageState extends State<MorseLearningPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  String _selectedCategory = '全部';

  final Map<String, List<String>> _categories = {
    '全部': [],
    '字母': 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''),
    '数字': '0123456789'.split(''),
    '标点': ['.', ',', '?', "'", '!', '/', '(', ')', '&', ':', ';', '=', '+', '-', '_', '"', '\$', '@'],
  };

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    // 全部类别包含所有字符
    _categories['全部'] = MorseTranslator.getSupportedCharacters()
        .where((c) => c != ' ')
        .toList();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  List<String> _getFilteredCharacters() {
    return _categories[_selectedCategory] ?? [];
  }

  Widget _buildCharacterCard(String char) {
    final morse = MorseTranslator.getCharMorse(char);
    
    return Card(
      elevation: 2,
      child: InkWell(
        onTap: () {
          // 可以添加音效播放功能
          _showCharacterDetail(char, morse ?? '');
        },
        borderRadius: BorderRadius.circular(16),
        child: Container(
          padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 12),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                char,
                style: TextStyle(
                  fontSize: 32,
                  fontWeight: FontWeight.bold,
                  color: Theme.of(context).colorScheme.primary,
                ),
              ),
              const SizedBox(height: 12),
              Text(
                morse ?? '',
                style: const TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.w500,
                  fontFamily: 'monospace',
                ),
                textAlign: TextAlign.center,
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _showCharacterDetail(String char, String morse) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(
          char,
          style: const TextStyle(fontSize: 48, fontWeight: FontWeight.bold),
          textAlign: TextAlign.center,
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              padding: const EdgeInsets.all(20),
              decoration: BoxDecoration(
                color: Theme.of(context).colorScheme.primaryContainer,
                borderRadius: BorderRadius.circular(12),
              ),
              child: Text(
                morse,
                style: TextStyle(
                  fontSize: 36,
                  fontWeight: FontWeight.bold,
                  fontFamily: 'monospace',
                  color: Theme.of(context).colorScheme.onPrimaryContainer,
                ),
              ),
            ),
            const SizedBox(height: 20),
            const Text(
              '• 点（.）：短音\n• 划（-）：长音\n• 长音时长约为短音的三倍',
              style: TextStyle(fontSize: 14),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  Widget _buildLearningTab() {
    final characters = _getFilteredCharacters();
    
    return Column(
      children: [
        // 分类选择器
        Container(
          padding: const EdgeInsets.all(16),
          child: SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              children: _categories.keys.map((category) {
                final isSelected = _selectedCategory == category;
                return Padding(
                  padding: const EdgeInsets.only(right: 8),
                  child: ChoiceChip(
                    label: Text(category),
                    selected: isSelected,
                    onSelected: (selected) {
                      if (selected) {
                        setState(() {
                          _selectedCategory = category;
                        });
                      }
                    },
                  ),
                );
              }).toList(),
            ),
          ),
        ),
        
        // 字符网格
        Expanded(
          child: characters.isEmpty
              ? const Center(child: Text('没有可显示的字符'))
              : GridView.builder(
                  padding: const EdgeInsets.all(16),
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 3,
                    crossAxisSpacing: 12,
                    mainAxisSpacing: 12,
                    childAspectRatio: 1.0,
                  ),
                  itemCount: characters.length,
                  itemBuilder: (context, index) {
                    return _buildCharacterCard(characters[index]);
                  },
                ),
        ),
      ],
    );
  }

  Widget _buildQuickStartTab() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // 快速开始卡片
          Card(
            color: Theme.of(context).colorScheme.primaryContainer,
            child: Padding(
              padding: const EdgeInsets.all(20),
              child: Column(
                children: [
                  Icon(
                    Icons.school,
                    size: 64,
                    color: Theme.of(context).colorScheme.primary,
                  ),
                  const SizedBox(height: 16),
                  Text(
                    '开始学习摩尔斯电码',
                    style: Theme.of(context).textTheme.headlineSmall?.copyWith(
                      fontWeight: FontWeight.bold,
                    ),
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 8),
                  Text(
                    '选择下面的学习模式开始你的学习之旅',
                    style: Theme.of(context).textTheme.bodyMedium,
                    textAlign: TextAlign.center,
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(height: 24),
          
          // 学习模式选项
          _buildModeCard(
            title: '浏览字符表',
            description: '查看所有字符及其对应的摩尔斯电码',
            icon: Icons.list_alt,
            color: Colors.blue,
            onTap: () {
              _tabController.animateTo(0);
            },
          ),
          const SizedBox(height: 12),
          
          _buildModeCard(
            title: '初级测验',
            description: '从字母开始，学习基础的摩尔斯电码',
            icon: Icons.play_circle_outline,
            color: Colors.green,
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const MorseQuizPage(
                    category: '字母',
                    difficulty: QuizDifficulty.easy,
                  ),
                ),
              );
            },
          ),
          const SizedBox(height: 12),
          
          _buildModeCard(
            title: '中级测验',
            description: '包含字母和数字的综合练习',
            icon: Icons.trending_up,
            color: Colors.orange,
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const MorseQuizPage(
                    category: '全部',
                    difficulty: QuizDifficulty.medium,
                  ),
                ),
              );
            },
          ),
          const SizedBox(height: 12),
          
          _buildModeCard(
            title: '高级测验',
            description: '包含所有字符的终极挑战',
            icon: Icons.stars,
            color: Colors.red,
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const MorseQuizPage(
                    category: '全部',
                    difficulty: QuizDifficulty.hard,
                  ),
                ),
              );
            },
          ),
          const SizedBox(height: 24),
          
          // 学习技巧卡片
          Card(
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Icon(
                        Icons.lightbulb_outline,
                        color: Theme.of(context).colorScheme.primary,
                      ),
                      const SizedBox(width: 8),
                      Text(
                        '学习技巧',
                        style: Theme.of(context).textTheme.titleLarge?.copyWith(
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 12),
                  const Text('📝 从常用字母开始\n'
                      '   E (.), T (-), A (.-), I (..), N (-.) 等\n\n'
                      '🎵 记住节奏和韵律\n'
                      '   把电码想象成音乐节奏\n\n'
                      '⏰ 每天练习 10-15 分钟\n'
                      '   持续学习比一次长时间学习更有效\n\n'
                      '🎯 先掌握字母，再学数字和标点\n'
                      '   循序渐进，稳步提升\n\n'
                      '✍️ 尝试手写电码\n'
                      '   动手练习有助于记忆',
                  ),
                ],
              ),
            ),
          ),
          
          const SizedBox(height: 16),
          
          // 常用缩写卡片
          Card(
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Icon(
                        Icons.info_outline,
                        color: Theme.of(context).colorScheme.secondary,
                      ),
                      const SizedBox(width: 8),
                      Text(
                        '常用摩尔斯缩写',
                        style: Theme.of(context).textTheme.titleLarge?.copyWith(
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 12),
                  const Text('SOS  (...---...) - 求救信号\n'
                      'CQ   (-.-. --.-) - 呼叫任何电台\n'
                      'OK   (--- -.-) - 好的，明白\n'
                      'TNX  (- -. -..-) - 谢谢\n'
                      '73   (--... ...--) - 最美好的祝愿',
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildModeCard({
    required String title,
    required String description,
    required IconData icon,
    required Color color,
    required VoidCallback onTap,
  }) {
    return Card(
      elevation: 2,
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(16),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Row(
            children: [
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: color.withOpacity(0.2),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Icon(icon, color: color, size: 32),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      title,
                      style: const TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      description,
                      style: TextStyle(
                        fontSize: 14,
                        color: Theme.of(context).textTheme.bodySmall?.color,
                      ),
                    ),
                  ],
                ),
              ),
              const Icon(Icons.chevron_right),
            ],
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '学习摩尔斯电码',
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
        bottom: TabBar(
          controller: _tabController,
          tabs: const [
            Tab(icon: Icon(Icons.grid_view), text: '字符表'),
            Tab(icon: Icon(Icons.rocket_launch), text: '快速开始'),
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          _buildLearningTab(),
          _buildQuickStartTab(),
        ],
      ),
    );
  }
}

